<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
<!--        <el-tabs v-model="loginType" @tab-click="getList(1)">-->
<!--          <el-tab-pane :label="item.name" :name="item.type.toString()" v-for="(item,index) in headeNum" :key="index"/>-->
<!--        </el-tabs>-->
        <div class="container">
          <el-form inline size="small" :model="userFrom" ref="userFrom" :label-position="labelPosition"  label-width="100px">
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                <el-col v-bind="grid">
                  <el-form-item label="用户搜索：">
                    <el-input v-model="userFrom.keyWord" placeholder="请输入姓名或手机号" clearable  class="selWidth"/>
                  </el-form-item>
                </el-col>
              </el-col>
<!--              <template v-if="collapse">-->
<!--                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">-->
<!--                  <el-col v-bind="grid">-->
<!--                    <el-form-item label="访问情况：">-->
<!--                      <el-select v-model="userFrom.accessType" placeholder="请选择"  class="selWidth" clearable>-->
<!--                        <el-option :value="0" label="全部"></el-option>-->
<!--                        <el-option :value="1" label="首次访问"></el-option>-->
<!--                        <el-option :value="2" label="时间段访问过"></el-option>-->
<!--                        <el-option :value="3" label="时间段未访问"></el-option>-->
<!--                      </el-select>-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col v-bind="grid">-->
<!--                    <el-form-item label="性别：">-->
<!--                      <el-radio-group v-model="userFrom.sex" type="button"  class="selWidth">-->
<!--                        <el-radio-button label="">-->
<!--                          <span>全部</span>-->
<!--                        </el-radio-button>-->
<!--                        <el-radio-button label="0">-->
<!--                          <span>未知</span>-->
<!--                        </el-radio-button>-->
<!--                        <el-radio-button label="1">-->
<!--                          <span>男</span>-->
<!--                        </el-radio-button>-->
<!--                        <el-radio-button label="2">-->
<!--                          <span>女</span>-->
<!--                        </el-radio-button>-->
<!--                        <el-radio-button label="3">-->
<!--                          <span>保密</span>-->
<!--                        </el-radio-button>-->
<!--                      </el-radio-group>-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-col>-->
<!--              </template>-->
              <el-col  :xs="24" :sm="24" :md="24" :lg="6" :xl="6" class="text-right userFrom">
                <el-form-item>
                  <el-button label="default" class="mr15" icon="el-icon-search" size="mini" type="primary"  @click="userSearchs">搜索</el-button>
                  <el-button class="ResetSearch mr10" @click="reset('userFrom')" icon="el-icon-refresh" size="mini">重置</el-button>
<!--                  <a class="ivu-ml-8" @click="collapse = !collapse">-->
<!--                    <template v-if="!collapse">-->
<!--                      展开 <i class="el-icon-arrow-down"></i>-->
<!--                    </template>-->
<!--                    <template v-else>-->
<!--                      收起 <i class="el-icon-arrow-up"></i>-->
<!--                    </template>-->
<!--                  </a>-->
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <el-table
        ref="table"
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        @selection-change="onSelectTab"
        highlight-current-row
        :header-cell-style=" {fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border
        >
<!--        <el-table-column type="expand">-->
<!--          <template slot-scope="props">-->
<!--            <el-form label-position="left" inline class="demo-table-expand">-->
<!--              <el-form-item label="首次访问：">-->
<!--                <span>{{ props.row.crtTimeText | filterEmpty }}</span>-->
<!--              </el-form-item>-->
<!--&lt;!&ndash;              <el-form-item label="近次访问：">&ndash;&gt;-->
<!--&lt;!&ndash;                <span>{{ props.row.lastLoginTime | filterEmpty }}</span>&ndash;&gt;-->
<!--&lt;!&ndash;              </el-form-item>&ndash;&gt;-->
<!--              <el-form-item label="手机号：">-->
<!--                <span>{{ props.row.mobile | filterEmpty }}</span>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="备注：">-->
<!--                <span>{{ props.row.data | filterEmpty }}</span>-->
<!--              </el-form-item>-->
<!--            </el-form>-->
<!--          </template>-->
<!--        </el-table-column>-->
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
        <el-table-column
          prop="id"
          label="ID"
          min-width="80"
        ><template slot-scope="scope">
        <span>{{scope.row.id | filterEmpty  }}</span>
      </template>
        </el-table-column>
        <el-table-column
        label="头像" min-width="80">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.faceUrl"
                :preview-src-list="[scope.row.faceUrl]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="昵称"
          min-width="140"
        >
          <template slot-scope="scope">
            <span>{{scope.row.userName | filterEmpty  }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="手机号"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{scope.row.mobile | filterEmpty}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          min-width="100"
        >
          <template slot-scope="scope">
            <span style="color: red" v-if="scope.row.status==1">未授权</span>
            <span style="color: #1BBE6B" v-else-if="scope.row.status==2">已授权</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="130" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click.native="empower(scope.row.id,2)" v-if="checkPermi(['admin:user:givePermissions'])&&scope.row.status===1">授权</el-button>
            <el-button type="danger" size="mini" @click.native="empower(scope.row.id,1)" v-if="checkPermi(['admin:user:revoke'])&&scope.row.status===2">取消授权</el-button>
            <el-button icon="el-icon-edit" type="primary" size="mini" @click.native="onDetails(scope.row.id)" v-if="checkPermi(['admin:user:detail'])">用户详情</el-button>
<!--            <el-dropdown trigger="click">-->
<!--              <span class="el-dropdown-link">-->
<!--                更多<i class="el-icon-arrow-down el-icon&#45;&#45;right" />-->
<!--              </span>-->
<!--              <el-dropdown-menu slot="dropdown">-->
<!--                <el-dropdown-item @click.native="onDetails(scope.row.id)" v-if="checkPermi(['admin:user:detail'])">用户详情</el-dropdown-item>-->
<!--                <el-dropdown-item @click.native="editPoint(scope.row.id)" v-if="checkPermi(['admin:user:score'])">积分</el-dropdown-item>-->
<!--&lt;!&ndash;                <el-dropdown-item @click.native="setPhone(scope.row)" v-if="checkPermi(['admin:user:modify:phone'])">修改手机号</el-dropdown-item>&ndash;&gt;-->
<!--              </el-dropdown-menu>-->
<!--            </el-dropdown>-->
          </template>
        </el-table-column>
        </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[15, 30, 45, 60]"
          :page-size="userFrom.limit"
          :current-page="userFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!--编辑-->
    <el-dialog
      title="编辑"
      :visible.sync="visible"
      width="600px"
    >
      <edit-from v-if="visible" :id="id" @resetForm="resetForm"></edit-from>
    </el-dialog>
    <!--积分余额-->
    <el-dialog
      title="积分"
      :visible.sync="VisiblePoint"
      width="600px"
      :close-on-click-modal="false"
      :before-close="handlePointClose">
      <el-form :model="PointValidateForm" ref="PointValidateForm" label-width="100px" class="demo-dynamic" v-loading="loadingPoint">
        <el-form-item
          label="修改积分"
          required
        >
          <el-radio-group v-model="PointValidateForm.integralType">
            <el-radio :label="1">提交随手拍增加</el-radio>
            <el-radio :label="2">立案受理增加</el-radio>
            <el-radio :label="3">核销减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="积分"
          required
        >
          <el-input-number type="text" step-strictly v-model="PointValidateForm.score" :min="0" :max="999999"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePointClose">取 消</el-button>
        <el-button type="primary" :loading="loadingBtn" @click="submitPointForm('PointValidateForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!--账户详情-->
    <el-dialog
      title="用户详情"
      :visible.sync="Visible"
      width="1100px"
      v-if="id"
      :before-close="Close">
      <user-details ref="userDetails" :id="id" v-if="Visible"></user-details>
    </el-dialog>
  </div>
</template>

<script>
import {
  userListApi,
  groupListApi,
  levelListApi,
  tagListApi,
  groupPiApi,
  tagPiApi,
  foundsApi,
  updateSpreadApi,
  updatePhoneApi,
  givePermissionsApi
} from '@/api/user'
  import editFrom from './edit'
  import userDetails from './userDetails'
  import userList from '@/components/userList'
  import Cookies from 'js-cookie'
  import { checkPermi } from "@/utils/permission"; // 权限判断函数
  import {Debounce} from '@/utils/validate'
  export default {
    name: 'UserIndex',
    components:{ editFrom, userDetails,userList },
    filters: {
      sexFilter(status) {
        const statusMap = {
          0: '未知',
          1: '男',
          2: '女',
          3: '保密'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        loadingBtn: false,
        PointValidateForm: {
          integralType: 1,
          score: 0,
          id: ''
        },
        loadingPoint: false,
        VisiblePoint: false,
        visible: false,
        userIds: '',
        dialogVisible: false,
        labelPosition:'right',
        collapse: false,
        props: {
          children: 'child',
          label: 'name',
          value: 'name',
          emitPath: false
        },
        headeNum: [
          { 'type': '', 'name': '全部用户' },
        ],
        listLoading: true,
        tableData: {
          data: [],
          total: 0
        },
        loginType: '',
        userFrom: {
          //: 0,
          //dateLimit: '',
          keyWord: '',
          page: 1,
          limit: 15,
        },
        grid: {
          xl: 8,
          lg: 12,
          md: 12,
          sm: 24,
          xs: 24
        },
        selectedData: [],
        timeVal: [],
        dynamicValidateForm:{
          groupId: []
        },
        loading: false,
        selectionList: [],
        id: 0,
        Visible: false,
        multipleSelectionAll: [],
        idKey:'id',
      }
    },
    activated(){
      this.userFrom.keywords = '';
      this.loginType = '0';
      this.getList(1);
    },
    mounted() {
      this.getList()
    },
    methods: {
      checkPermi,
      setPhone(row) {
        this.$prompt('修改手机号', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputErrorMessage: '请输入修改手机号',
          inputType: 'text',
          inputValue: row.phone,
          inputPlaceholder: '请输入手机号',
          closeOnClickModal: false,
          inputValidator: (value) => {
            if (!value) return '请填写手机号'
            // if (!/^1[3456789]\d{9}$/.test(value)) return '手机号格式不正确!'
            // if(!value) return '输入不能为空'
          }
        }).then(({value}) => {
          //updatePhoneApi({id: row.id,phone: value}).then(() => {
            this.$message.success('编辑成功')
            this.getList();
          //})
        }).catch(() => {
          this.$message.info('取消输入')
        })
      },

      resetForm(){
        this.visible = false;
      },
      reset(formName) {
        this.userFrom = {
            // accessType: 0,
            // dateLimit: '',
            keywords: '',
            page: 1,
            limit: 15,
        }
        this.timeVal = []
        this.getList()
      },

      // 积分清零
      clearScore(){
        if (this.selectionList.length==0){
          this.$message.warning('请选择用户')
        }
        else {
          this.listLoading = true
          this.$confirm('确认用户积分清零').then(() => {

              this.$message.success('积分清零成功')
              this.getList()
              this.listLoading = false

            // this.selectionList = selection;
            // setTimeout(() => {
            //   this.changePageCoreRecordData()
            //   let data = [];
            //   if(this.multipleSelectionAll.length){
            //     this.multipleSelectionAll.map((item) => {
            //       data.push(item.id)
            //     });
            //     this.userIds = data.join(',');
            //     console.log(this.userIds)
            //   }
            // }, 50)

          })
        }
      },
      Close() {
        this.Visible = false
      },
      // 账户详情
      onDetails(id){
        this.id = id
        this.Visible = true
      },
      // 授权
      empower(id,status){
        givePermissionsApi({id:id,status:status}).then(res => {
          this.$message.success('设置成功')
          this.getList()
        }).catch(() => {
        })
      },
      // 积分余额
      editPoint(id) {
        this.id = id
        this.VisiblePoint = true
      },
      // 积分余额
      submitPointForm:Debounce(function(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.PointValidateForm.id = this.id
            this.loadingBtn = true
            if (this.PointValidateForm.integralType==3)
              this.PointValidateForm.score = -this.PointValidateForm.score
            foundsApi(this.PointValidateForm).then(res => {
              this.$message.success('设置成功')
              this.loadingBtn = false
              this.handlePointClose()
              this.getList()
            }).catch(() => {
              this.loadingBtn = false
            })
          } else {
            return false
          }
        })
      }),
      // 积分余额
      handlePointClose() {
        this.VisiblePoint = false
        this.PointValidateForm = {
          integralType: 1,
          integralValue: 0,
          id: ''
        }
      },
      editUser(id,data) {
        this.id = id
        this.data=data
        this.visible = true
        console.log(this.data)
      },
      handleClose(){
        this.dialogVisible = false
        this.$refs['dynamicValidateForm'].resetFields();
      },
      // 全选
      onSelectTab (selection) {
        this.selectionList = selection;
        setTimeout(() => {
          this.changePageCoreRecordData()
          let data = [];
          if(this.multipleSelectionAll.length){
            this.multipleSelectionAll.map((item) => {
              data.push(item.id)
            });
            this.userIds = data.join(',');
          }
        }, 50)
      },
      // 搜索
      userSearchs () {
        this.userFrom.page = 1;
        this.getList();
      },
      // 具体日期
      onchangeTime (e) {
        this.timeVal = e;
        this.userFrom.dateLimit = e ? this.timeVal.join(',') : '';
      },

      // 列表
      getList(num) {
        this.listLoading = true
        this.userFrom.page = num ? num : this.userFrom.page;
        this.userFrom.userType = this.loginType
        if(this.loginType == 0) this.userFrom.userType =''
        userListApi(this.userFrom).then(res => {
        //后期接口调用
          this.tableData.data = res.list
          this.tableData.total = res.count
          this.$nextTick(function() {
            this.setSelectRow()// 调用跨页选中方法
          })
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        })
        this.checkedCities = this.$cache.local.has('user_stroge') ? this.$cache.local.getJSON('user_stroge') : this.checkedCities;
      },
      // 设置选中的方法
      setSelectRow() {
        if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
          return
        }
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const selectAllIds = []
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey])
        })
        this.$refs.table.clearSelection()
        for (var i = 0; i < this.tableData.data.length; i++) {
          if (selectAllIds.indexOf(this.tableData.data[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="table"
            this.$refs.table.toggleRowSelection(this.tableData.data[i], true)
          }
        }
      },
      // 记忆选择核心方法
      changePageCoreRecordData() {
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const that = this
        // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
        if (this.multipleSelectionAll.length <= 0) {
          this.multipleSelectionAll = this.selectionList
          return
        }
        // 总选择里面的key集合
        const selectAllIds = []
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey])
        })
        const selectIds = []
        // 获取当前页选中的id
        this.selectionList.forEach(row => {
          selectIds.push(row[idKey])
          // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
          if (selectAllIds.indexOf(row[idKey]) < 0) {
            that.multipleSelectionAll.push(row)
          }
        })
        const noSelectIds = []
        // 得到当前页没有选中的id
        this.tableData.data.forEach(row => {
          if (selectIds.indexOf(row[idKey]) < 0) {
            noSelectIds.push(row[idKey])
          }
        })
        noSelectIds.forEach(id => {
          if (selectAllIds.indexOf(id) >= 0) {
            for (let i = 0; i < that.multipleSelectionAll.length; i++) {
              if (that.multipleSelectionAll[i][idKey] == id) {
                // 如果总选择中有未被选中的，那么就删除这条
                that.multipleSelectionAll.splice(i, 1)
                break
              }
            }
          }
        })
      },
      pageChange(page) {
        this.changePageCoreRecordData()
        this.userFrom.page = page
        this.getList()
      },
      handleSizeChange(val) {
        this.changePageCoreRecordData()
        this.userFrom.limit = val
        this.getList()
      },
      // 删除
      handleDelete(id, idx) {
        this.$modalSure().then(() => {
          //productDeleteApi(id).then(() => {
            this.$message.success('删除成功')
            this.getList()
          //})
        })
      },
    }
  }
</script>

<style scoped lang="scss">
  /*.timeBox{*/
    /*width: 100%;*/
    /*::v-deep.el-form-item__content{*/
      /*width: 87% !important;*/
    /*}*/
  /*}*/
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 12px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .text-right{
    text-align: right;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 33.33%;
  }
  .selWidth{
    width: 100% !important;
  }
  .seachTiele{
    line-height: 30px;
  }
  .container{
    min-width: 821px;
    ::v-deep.el-form-item{
      width: 100%;
    }
    ::v-deep.el-form-item__content{
      width: 72%;
    }
  }
  .ivu-ml-8{
    font-size: 12px;
    color: #1682e6;
  }
  .btn_bt{
    border-top:1px dashed #ccc;
    padding-top: 20px;
  }
  .relative{
    position: relative;
  }
</style>
